
package com.tools.cleanmaster.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.NoLeakHandler;

import java.util.Timer;
import java.util.TimerTask;

public class CommonDialog extends Dialog {

    private static class MyHandler extends NoLeakHandler<CommonDialog> {
        MyHandler(CommonDialog context) {
            super(context);
        }

        @Override
        protected void processMessage(CommonDialog context, Message msg) {
            if (msg.what == MSG_DISMISS_TIMER_UPDATED) {
                context.mTimerListener.onTimeUpdated(msg.arg1);
            }
        }
    }

    private static final String TAG = "CommonDialog";

    public interface TimerListener {
        void onTimeUpdated(int leftSeconds);
    }

    public static final int DEFAULT_BTN_LEFT = 1;
    public static final int DEFAULT_BTN_MID = 2;
    public static final int DEFAULT_BTN_RIGHT = 3;

    public static final int SUGGESTIVE_ON = 1;
    public static final int SUGGESTIVE_OFF = 0;

    private static final int MSG_DISMISS_TIMER_UPDATED = 1;
    private Button mDefaultBtn;
    private ScrollView mContentHolder;
    private LinearLayout mLinearLayout;
    private View mLayoutButtons;
    private Context mContext;
    private Button mOkButton;
    private LinearLayout mPLayout;
    TextView mTitleView;

    private TimerListener mTimerListener;
    private Timer mTimer;
    private int mLeftSeconds;
    private Handler mHandler = new MyHandler(this);

    public CommonDialog(Context context) {
        super(context, R.style.MyTheme_CustomDialog);
        setContentView(R.layout.common_dialog);
        mContentHolder = findViewById(R.id.content_holder);
        mLinearLayout = findViewById(R.id.content_holder_lin);
        mLayoutButtons = findViewById(R.id.btn_panel);
        mOkButton = findViewById(R.id.ok_btn);
        mTitleView = findViewById(R.id.title);
        mPLayout = findViewById(R.id.all_lin);
        mContext = context;
        setCanceledOnTouchOutside(true);
    }

    public void setTitle(int resId) {
        mTitleView.setText(getContext().getString(resId).toUpperCase());
    }

    public void setTitle(String title) {
        mTitleView.setText(title.toUpperCase());
    }

    public void setContentView(View view) {
        ViewGroup contentHolder = mContentHolder;
        contentHolder.removeAllViews();
        contentHolder.addView(view);
    }

    public void setButtonButtomMargin(int px) {
        mLayoutButtons.setPadding(mLayoutButtons.getPaddingLeft(), mLayoutButtons.getPaddingTop(),
                mLayoutButtons.getPaddingRight(), px);
    }

    public void setContentPadding(int width) {
        mContentHolder.setPadding(width, mContentHolder.getPaddingTop(), width,
                mContentHolder.getPaddingBottom());
    }

    public void setContentPadding(int left, int top, int right, int bottom) {
        mContentHolder.setPadding(left, top, right, bottom);
    }

    public void addContentView(View view) {
        ViewGroup contentHolder = mLinearLayout;
        contentHolder.addView(view);
    }

    public void addIndexContentView(View view, int index) {
        if (index < 0) {
            addContentView(view);
        }
        ViewGroup contentHolder = mLinearLayout;
        contentHolder.addView(view, index);
    }

    public void setMessage(int resId) {
        TextView content = findViewById(R.id.message);
        content.setText(resId);
        content.setVisibility(View.VISIBLE);
    }

    public void setMessage(CharSequence msg) {
        TextView content = findViewById(R.id.message);
        content.setText(msg);
        content.setVisibility(View.VISIBLE);
    }

    public CheckBox setCheckBox(boolean initialValue, CharSequence text) {
        View checkBoxParent = findViewById(R.id.checkbox_parent);
        final CheckBox cb = checkBoxParent.findViewById(R.id.checkbox);
        cb.setChecked(initialValue);

        final TextView tv = checkBoxParent.findViewById(R.id.checkbox_message);
        tv.setText(text);
        checkBoxParent.setVisibility(View.VISIBLE);

        checkBoxParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cb.toggle();
            }
        });
        return cb;
    }

    public CheckBox setCheckBox(boolean initialValue, int resId) {
        return setCheckBox(initialValue, mContext.getText(resId));
    }

    public void setOkBtn(int resId, View.OnClickListener clickListener, int suggestive) {
        String text = null;
        if (resId != 0) {
            text = CleanApplication.getInstance().getResources().getString(resId);
        }
        setOkBtn(text, clickListener, suggestive);
    }

    public void setOkBtn(String text, View.OnClickListener clickListener, int suggestive) {
        mLayoutButtons.setVisibility(View.VISIBLE);
        Button okBtn = mOkButton;
        setButtonStyle(okBtn, suggestive);
        okBtn.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(text)) {
            okBtn.setText(text.toUpperCase());
        }
        if (clickListener != null) {
            okBtn.setOnClickListener(new ExternalListener(clickListener));
        } else {
            okBtn.setOnClickListener(new CloseListener());
        }
    }

    public void setOkBtnDeleteBackground() {
        if (mOkButton != null) {
//            ColorStateList color = mContext.getResources().getColorStateList(
//                    R.color.button_delete_color);
//            mOkButton.setTextColor(color);
//            mOkButton.setBackgroundResource(R.drawable.delete_button);
        }
    }

    public void setOkBtn(String text, View.OnClickListener clickListener) {
        setOkBtn(text, clickListener, CommonDialog.SUGGESTIVE_OFF);
    }

    private void setButtonStyle(Button button, int suggestive) {
//        if (suggestive == SUGGESTIVE_ON) {
//            ColorStateList color = mContext.getResources().getColorStateList(
//                    R.color.suggestive_button_color);
//            button.setTextColor(color);
//            button.setBackgroundResource(R.drawable.suggestive_public_button);
//        } else {
//            ColorStateList color = mContext.getResources().getColorStateList(
//                    R.color.public_button_color);
//            button.setTextColor(color);
//            button.setBackgroundResource(R.drawable.common_button);
//        }
    }

    public void setOkBtn(int resId, View.OnClickListener clickListener) {
        setOkBtn(resId, clickListener, SUGGESTIVE_OFF);
    }

    /**
     * This method should have click listener and dismiss dialog by yourself
     */
    public void setOkBtnNotDismiss(int resId, View.OnClickListener clickListener) {
        mLayoutButtons.setVisibility(View.VISIBLE);
        Button okBtn = mOkButton;
        okBtn.setVisibility(View.VISIBLE);
        if (resId > 0) {
            okBtn.setText(resId);
        }
        okBtn.setOnClickListener(clickListener);
    }

    public void setBtnEnable(int whichBtn, boolean enable) {
        Button button = null;

        if (whichBtn == DEFAULT_BTN_LEFT) {
            button = mOkButton;
        } else if (whichBtn == DEFAULT_BTN_MID) {
            button = findViewById(R.id.mid_btn);
        } else if (whichBtn == DEFAULT_BTN_RIGHT) {
            button = findViewById(R.id.cancel_btn);
        } else {
            button = null;
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.w(TAG, "Set Bad bt: " + whichBtn);
            }
        }

        if (button != null) {
            button.setEnabled(enable);
        }
    }

    public void setCancelBtn(int resId, View.OnClickListener clickListener, int suggestive) {
        String text = null;
        if (resId != 0) {
            text = CleanApplication.getInstance().getResources().getString(resId);
        }
        setCancelBtn(text, clickListener, suggestive);
    }

    public void setCancelBtn(int resId, View.OnClickListener clickListener) {
        String text = null;
        if (resId != 0) {
            text = CleanApplication.getInstance().getResources().getString(resId);
        }
        setCancelBtn(text, clickListener);
    }

    public void setCancelBtn(String text, View.OnClickListener clickListener) {
        setCancelBtn(text, clickListener, CommonDialog.SUGGESTIVE_OFF);
    }

    public void setCancelBtn(String text, View.OnClickListener clickListener, int suggestive) {
        mLayoutButtons.setVisibility(View.VISIBLE);
        Button cancelBtn = findViewById(R.id.cancel_btn);
        setButtonStyle(cancelBtn, suggestive);
        cancelBtn.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(text)) {
            cancelBtn.setText(text.toUpperCase());
        }

        if (clickListener != null) {
            cancelBtn.setOnClickListener(new ExternalListener(clickListener));
        } else {
            cancelBtn.setOnClickListener(new CloseListener());
        }

        findViewById(R.id.line1).setVisibility(View.VISIBLE);
    }

    public void setMidBtn(int resId, View.OnClickListener clickListener) {
        setMidBtn(resId, clickListener, SUGGESTIVE_OFF);
    }

    public void setMidBtn(int resId, View.OnClickListener clickListener, int suggestive) {
        Button midBtn = findViewById(R.id.mid_btn);
        midBtn.setVisibility(View.VISIBLE);
        setButtonStyle(midBtn, suggestive);
        if (resId > 0) {
            midBtn.setText(resId);
        }

        if (clickListener != null) {
            midBtn.setOnClickListener(new ExternalListener(clickListener));
        } else {
            midBtn.setOnClickListener(new CloseListener());
        }
        findViewById(R.id.line2).setVisibility(View.VISIBLE);
    }

    /**
     * Set the default button, which will be focused.
     *
     * @param whichBtn Must be one of {@link #DEFAULT_BTN_LEFT} or
     *                   {@link #DEFAULT_BTN_MID} or {@link #DEFAULT_BTN_RIGHT}
     */
    public void setDefaultButton(int whichBtn) {
        if (whichBtn == DEFAULT_BTN_LEFT) {
            mDefaultBtn = mOkButton;
        } else if (whichBtn == DEFAULT_BTN_MID) {
            mDefaultBtn = findViewById(R.id.mid_btn);
        } else if (whichBtn == DEFAULT_BTN_RIGHT) {
            mDefaultBtn = findViewById(R.id.cancel_btn);
        } else {
            mDefaultBtn = null;
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.w(TAG, "Bad default bt: " + whichBtn);
            }
        }

        if (mDefaultBtn != null) {
            mDefaultBtn.setSelected(true);
        }
    }

    public void showWithAutoDismiss(int seconds, TimerListener listener) {
        if (isShowing() || seconds <= 0) {
            return;
        }

        mLeftSeconds = seconds;
        mTimerListener = listener;
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                --mLeftSeconds;
                if (mTimerListener != null) {
                    mHandler.obtainMessage(MSG_DISMISS_TIMER_UPDATED,
                            mLeftSeconds, 0).sendToTarget();
                }
                if (mLeftSeconds == 0) {
                    mTimer.cancel();
                    dismiss();
                }
            }
        }, 1000, 1000);
        super.show();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mDefaultBtn != null) {
            mDefaultBtn.setSelected(false);
            mDefaultBtn = null;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
            return true; // ignore back key & search key
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            // Let super class to handle this key event
        }
        return super.dispatchKeyEvent(event);
    }

    private class CloseListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            cancel();
        }
    }

    private class ExternalListener implements View.OnClickListener {
        private View.OnClickListener mListener;

        public ExternalListener(View.OnClickListener listener) {
            mListener = listener;
        }

        @Override
        public void onClick(View v) {
            CommonDialog.this.dismiss();
            mListener.onClick(v);
        }
    }

    public void setImageView(int resid) {
        ImageView imageView = findViewById(R.id.common_image);
        imageView.setVisibility(View.VISIBLE);
        if (resid > 0) {
            imageView.setBackgroundResource(resid);
        }
    }

    public void addChildCenterView(View v) {
        if (mPLayout != null) {
            mPLayout.removeAllViews();
            LayoutParams layoutParams = (LayoutParams) mPLayout.getLayoutParams();
            layoutParams.gravity = Gravity.CENTER;
            mPLayout.addView(v, layoutParams);
        }
    }
}
